// pages/login/index.js
const {
  phoneLogin
} = require('../../api/login')
const config = require("../../config/config");

Page({

  /**
   * 页面的初始数据
   */
  data: {
    isAgree: true,
    currentIndex: 0,
    showPwd: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },
  login(e) {
    const {
      isAgree,
    } = this.data
    return new Promise((resolve, reject) => {
      if (!isAgree) {
        wx.showToast({
          title: '请先同意用户服务协议及隐私政策',
          icon: 'none'
        })
        reject()
        return
      }
      resolve()
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },
  changeStatus() {
    this.setData({
      showPwd: !this.data.showPwd
    })
  },
  changeIndex(e) {
    const index = e.currentTarget.dataset.index
    this.setData({
      currentIndex: parseInt(index)
    })
  },
  change(e){
    this.setData({
      isAgree:e.detail.value
    })
  },
  
  goto(e) {
    const url = e.currentTarget.dataset.url
    wx.navigateTo({
      url: url,
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  getUserProfile(e) {
    var that = this
    let newTime = Math.round(new Date())
    wx.showLoading({
      title: '登陆中',
    })
    wx.setStorageSync(config.storageKey.loginTime, newTime);
    wx.getUserProfile({
      desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: async function (res) {
        console.log(res)
        const {
          encryptedData,
          iv,
        } = res;
        const info = res.userInfo
        wx.login({
          success: async function (ress) {
            const param = {
              avatarUrl: info.avatarUrl,
              city: info.city,
              code: ress.code,
              country: info.city,
              encryptedData,
              iv,
              language: info.language,
              merchantId: 0,
              nickName: info.nickName,
              promoterId: 0,
              province: info.province,
              sex: info.gender,
              promoteUser: wx.getStorageSync('promoteUser'),
            }
            wx.hideLoading()
            const {
              result
            } = await wxLogin(param);
            const {
              userInfo,
              token,
            } = result
            wx.setStorageSync(config.storageKey.userId, userInfo.id);
            wx.setStorageSync(config.storageKey.token, token)
            that.fetchUserInfo()
            that.setData({
              userInfo,
              isLogin: true,
              isVip: (userInfo.isVip && userInfo.isVip) > 0,
            })
            if (userInfo.mobile == '') {
              return
            }
            wx.setStorageSync(config.storageKey.mobile, userInfo.mobile)

          }
        })

      },
      fail: function (res) {
        wx.hideLoading()
      }
    })

  },
  submit_code(e) {
    const params = e.detail.value
  },
  async submit_account(e) {
    this.login().then(async (res) => {

      const params = e.detail.value
      params.userType = 1;
      if(params.userAccount==''){
        wx.showToast({
          title: '请输入账号',
          icon:'none'
        })
        return
      }
      if(params.userPassword==''){
        wx.showToast({
          title: '请输入密码',
          icon:'none'
        })
        return
      }
      const {
        token,
        user
      } = await phoneLogin(params)
      wx.setStorageSync('token', token)
      wx.setStorageSync('userInfo', user)
            var pages = getCurrentPages()
      var prevpage = pages[pages.length - 2]
      prevpage.onLoad()
      setTimeout(() => {
              wx.navigateBack({
        delta: 1,
      })
      }, 500);


    })

  }
})